import { Injectable } from '@nestjs/common';
import { CreateClassicsDto} from './dto';
import { Repository,In, Not, ReturnDocument } from 'typeorm';
import { InjectRepository} from '@nestjs/typeorm';
import {Classics} from './entities/classics.entity';
import { v4 as uuidv4 } from 'uuid';
import {ResultData} from '../../common/utils/result';
@Injectable()
export class ClassicsService {
    constructor(
        @InjectRepository(Classics)
        private poetryRepository: Repository<Classics>,
      ) {}
    
    async create(classics: CreateClassicsDto) {
        classics.poetry_id = uuidv4();
        const res = await this.poetryRepository.insert(classics)
        return ResultData.ok(res);
    }

    async createJson(data: CreateClassicsDto[]) {
        try {
          // 为每条记录生成唯一 ID 并序列化字段
          const processedData = data.map((item) => ({
            ...item,
            poetry_id: uuidv4(),
            tags:item.tags?JSON.stringify(item.tags):"",
            paragraphs:item.paragraphs?JSON.stringify(item.paragraphs):"",
            prologue:item.prologue?item.prologue:'',
            notes:item.notes?JSON.stringify(item.notes):"",
            origin:item.origin?JSON.stringify(item.origin):"",
            content:item.content?JSON.stringify(item.content):"",
            abstract:item.abstract?JSON.stringify(item.abstract):"",
            preface:item.preface?JSON.stringify(item.preface):"",
            spells:item.spells?JSON.stringify(item.spells):"",
            type_name:"朱子家訓",
            type:'013',
          }));
      
          // 遍历数据逐条插入，捕获主键冲突错误
          for (const item of processedData) {
            try {
              await this.poetryRepository.insert(item); // 单条插入
            } catch (error) {
              // 检查是否为主键冲突错误
              if (error.code === 'ER_DUP_ENTRY') {
                console.warn(`Duplicate entry ignored for poetry_id: ${item.poetry_id}`);
                continue; // 忽略当前记录，继续下一条
              }
              throw error; // 如果是其他错误，则抛出
            }
          }
      
          return ResultData.ok();
        } catch (error) {
          return ResultData.fail(error.message || error);
        }
      }
}
